package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.yige.common.ResultUtil
import com.yige.service.ChenService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by sunhao on 2015/12/22 0022.
 */
@Controller
@RequestMapping("chen")
class ChenController {

    @Autowired
    ChenService chenService


    @RequestMapping("list.do")
    def list(Model model) {
        def list = chenService.findList()
        model.addAttribute("list", list)
        return "chen/list"
    }

    @RequestMapping("find")
    def find(String student, Model model) {
        def query = new BasicDBObject()
        if (!StringUtils.isEmpty(student)) {
            query.append("student", ~/${student}/)
        }
        def list = chenService.findListByQuery(query)
        model.addAttribute("list", list)
        return "chen/list"

    }

    @RequestMapping("add")
    @ResponseBody
    def add(String student, int n, double price) {
        def total = n * price
        def salary = total * 0.7
        def obj = [_id: UUID.randomUUID().toString(), student: student, n: n, price: price, salary: salary, total: total] as BasicDBObject
        boolean flag = chenService.insertOne(obj)
        return ResultUtil.recallAjax(flag)
    }

    @RequestMapping("delete")
    @ResponseBody
    def delete(@RequestParam(value = "_ids") List<String> _ids) {
        boolean flag = false
        _ids.each { _id ->
            flag = chenService.deleteOne(_id)
        }
        return ResultUtil.recallAjax(flag)
    }

    @RequestMapping("update")
    @ResponseBody
    def update(Object _id, String student, int n, double price) {
        def total = n * price
        def salary = total * 0.7
        def obj = [_id: _id, student: student, n: n, price: price, salary: salary, total: total] as BasicDBObject
        boolean flag = chenService.updateOne(_id, obj)
        return ResultUtil.recallAjax(flag)
    }

}
